package operation

import (
	"notabug.org/apiote/next-eeze/fs"
	
	"log"
	"strings"
	"errors"
)

// todo memguard masterPassword
func Get(username, label, url string, full, short bool, masterPassword string) (string, error) {
	if full && short {
		err := errors.New("Full and short specified at the same time")
		log.Fatal("Error. ", err)
		return "", err
	}
	// todo memguard
	passwords, err := fs.Read(masterPassword)
	if err != nil {
		return "", err
	}
	// todo memguard
	resultPasswords := []string{}
	// todo memguard
	for _, p := range passwords {
		if (username == "" || username == p.Username) &&
			(label == "" || label == p.Label) &&
			(url == "" || url == p.Url) {
			if short {
				resultPasswords = append(resultPasswords, p.Password)
			} else if full {
				resultPassword := p.Label
				if p.Url != "" {
					resultPassword = resultPassword + " ("+p.Url+")"
				}
				resultPassword += "\nUsername: "
				if p.Username != "" {
					resultPassword = resultPassword + p.Username
				} else {
					resultPassword = resultPassword + "-"
				}
				resultPassword += "\nPassword: " + p.Password
				if p.Notes != "" {
				resultPassword += "\n" + p.Notes
				}
				resultPasswords = append(resultPasswords, resultPassword)
			} else {
				resultPasswords = append(resultPasswords, p.Username+" / "+p.Password)
			}
		}
	}
	return strings.Join(resultPasswords, "\n\n"), nil
}

// todo memguard masterPassword
func List(masterPassword string) (string, error) {
	// todo memguard
	passwords, err := fs.Read(masterPassword)
	if err != nil {
		return "", err
	}
	// todo memguard
	resultPasswords := []string{}
	// todo memguard
	for _, p := range passwords {
		if p.Username != "" {
			resultPasswords = append(resultPasswords, p.Label+": "+p.Username)
		} else {
			resultPasswords = append(resultPasswords, p.Label)
		}
	}
	return strings.Join(resultPasswords, "\n"), nil
}
